import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/theme/theme_color.dart';

import '../../../global_easy_loading.dart';
import 'login_input_decorator.dart';

// class PhoneWithAreaCodeEntity {
//   String phone = '';
//   String areaCode = '86';
//   PhoneWithAreaCodeEntity();

//   factory PhoneWithAreaCodeEntity.create(String phone,
//       {String areaCode = '86'}) {
//     return PhoneWithAreaCodeEntity()
//       ..phone = phone
//       ..areaCode = areaCode;
//   }
//   Map<String, dynamic> get jsonValue {
//     var result = Map<String, dynamic>();
//     result["phone"] = this.phone;
//     result["areaCode"] = this.areaCode;
//     return result;
//   }
// }

class LoginAccountForm extends StatefulWidget {
  final FormFieldSetter<String>? onSaved;
  final TextEditingController? controller;
  final String? hintText;
  final FocusNode? focusNode;

  const LoginAccountForm({
    Key? key,
    this.onSaved,
    this.controller,
    this.focusNode,
    this.hintText,
  }) : super(key: key);

  @override
  _LoginAccountFormState createState() => _LoginAccountFormState();
}

class _LoginAccountFormState extends State<LoginAccountForm> {
  // String phone = '';
  // String areaCode = '86';
  String _account = '';

  @override
  void initState() {
    super.initState();
    String account = appContext.storage.getString("login_account") ?? '';
    // String cachePhone = appContext.storage.getString("login_phone") ?? '';
    // String cachePhoneArea = appContext.storage.getString('login_area') ?? '';

    // DLog('account${account.characters}');
    if (account != '') {
      // Map<String, dynamic> map = convert.json.decode(account);
      setState(() {
        _account = account;
        // if (cachePhoneArea != '') {
        //   areaCode = cachePhoneArea;
        // } else {
        //   areaCode = map['areaCode'];
        // }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextFormField(
        enableInteractiveSelection: false,
        initialValue: _account,

        controller: widget.controller,
        autofocus: false,
        focusNode: widget.focusNode,
        maxLength: 60,
        inputFormatters: [
          FilteringTextInputFormatter.deny(appContext.emojiRegexp)
        ],
        style: const TextStyle(
          color: ThemeColor.colorTextB1,
          fontSize: 14,
          // height: 1.5,
          fontWeight: FontWeight.w400,
        ),
        cursorColor: ThemeColor.primaryColor,
        decoration: LoginInputDecoration(
          hintText: widget.hintText ?? '',

          // prefixIcon: Container(
          //   padding: EdgeInsets.only(
          //     top: 0,
          //     left: 15,
          //     right: 5,
          //     bottom: 0,
          //   ),
          //   margin: EdgeInsets.only(right: 10),
          //   decoration: BoxDecoration(
          //     border: Border(
          //       right: BorderSide(color: Colors.white),
          //     ),
          //   ),
          //   child: GestureDetector(
          //     onTap: ClickUtils.debounce(() {
          //       showAreaAlert();
          //     }),
          //     child: Row(
          //       mainAxisAlignment: MainAxisAlignment.start,
          //       mainAxisSize: MainAxisSize.min,
          //       children: [
          //         Text(
          //           '+$areaCode',
          //           textAlign: TextAlign.center,
          //           style: TextStyle(
          //             color: Colors.white,
          //             fontSize: 16,
          //             fontWeight: FontWeight.bold,
          //           ),
          //         ),
          //         Icon(
          //           Icons.arrow_drop_down,
          //           color: Colors.white,
          //         ),
          //       ],
          //     ),
          //   ),
          // ),
        ),
        validator: (val) {
          if (val!.length < 6) {
            customShowToast(S.of(context).enter_valid_account);
            return '';
          }
          // if (areaCode == '86') {
          //   if (!RegexUtil.isMobileSimple(val!)) {
          //     customShowToast(S.of(context).enter_valid_phone);
          //     return '';
          //   }
          // } else if (!RegexUtil.matches('^\\d{6,25}\$', val!)) {
          //   customShowToast(S.of(context).enter_valid_phone);
          //   return '';
          // }
          return null;
        },
        onSaved: (val) {
          // PhoneWithAreaCodeEntity _phone = PhoneWithAreaCodeEntity.create(
          //   val!,
          //   areaCode: areaCode,
          // );
          // var value = convert.json.encode(_phone.jsonValue);
          // appContext.storage.setString("login_phone", value);
          // widget.onSaved!(_phone);
          _account = val!;
          // var value = convert.json.encode(_account);
          appContext.storage.setString("login_account", _account);
          if (widget.onSaved != null) {
            widget.onSaved!(_account);
          }
        },
        obscureText: false,
        // keyboardType: TextInputType.phone,
      ),
    );
  }

// void showAreaAlert() async {
//   List<AreaCodeData> list = [];
//   try {
//     list = await API.shared.login.areaList();
//     list.sort((left, right) => left.pinyinName.compareTo(right.pinyinName));
//   } catch (e) {
//     await UtilsOther.showCustomShowError(e);
//     // if (e is DioError) {
//     //   customShowToast(e.message);
//     // } else {
//     //   customShowToast(S().network_error);
//     // }
//     return;
//   }
//   var titleKey = '';
//   for (int i = 0; i < list.length; i++) {
//     var item = list[i];
//     var title = '';
//     try {
//       title = item.pinyinName.substring(0, 1).toUpperCase();
//     } catch (e) {
//       title = '#';
//     }
//     if (titleKey != title) {
//       titleKey = title;
//       item.firstName = titleKey;
//     }
//   }
//   Navigator.push(
//       context,
//       NNPopupRoute(
//           needSafe: true,
//           alignment: Alignment.bottomCenter,
//           onClick: () {
//             Navigator.of(context).pop();
//           },
//           child: LoginAreaCodePage(
//               onClick: (AreaCodeData item) {
//                 setState(() {
//                   areaCode = item.areaCode;
//                 });
//               },
//               data: list)));
// }
}
